package com.zw.yzk.kabu.data.repository;


import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.cache.store.AddressStore;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.ShippingAddressEntity;
import com.zw.yzk.kabu.data.network.service.DeleteShippingAddressService;
import com.zw.yzk.kabu.data.network.task.DeleteShippingAddressTask;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2016/12/24.
 */

public class DeleteShippingAddressRepository extends CommonRepository {

    @Inject
    AddressStore addressStore;

    @Inject
    public DeleteShippingAddressRepository() {

    }

    @Override
    protected Observable connectServer(Task task) {
        DeleteShippingAddressService service = ServiceGenerator.createService(DeleteShippingAddressService.class);
        DeleteShippingAddressTask deleteShippingAddressTask = (DeleteShippingAddressTask) task;

        return service.deleteShippingAddress(deleteShippingAddressTask.userId, deleteShippingAddressTask.accessToken, deleteShippingAddressTask.addressId);
    }

    @Override
    protected Func1<ShippingAddressEntity, Observable> getServerData() {
        return new Func1<ShippingAddressEntity, Observable>() {
            @Override
            public Observable call(ShippingAddressEntity entity) {
                updateAddress(entity);
                return Observable.just(entity);
            }
        };
    }

    /**
     * 更新user信息,设置默认收货地址
     *
     * @param entity
     */
    private void updateAddress(ShippingAddressEntity entity) {
        if (entity.result.addressList == null || entity.result.addressList.isEmpty()) {
            addressStore.clear();
        } else {
            for (ShippingAddressEntity.Address address : entity.result.addressList) {
                if (address.isDefault == 1) {
                    addressStore.refresh(address);
                }
            }
        }
    }
}
